//
//  YJDZFffment.m
//  YJDSDK
//
//  Created by SKL on 2017/11/8.
//  Copyright © 2017年 SKL. All rights reserved.
//

#import "YJDPlatform.h"
#import "YJDZFController.h"
#import "YJDLoginViewController.h"
#import "YJDRegisterViewController.h"
#import "YJDUserBtn.h"
#import "LoadingViewController.h"
@interface YJDPlatform()<YJDZFControllerDelegate,YJDUserBtnDelegate,YJDLoginViewControllerDelegate>
{
    NSString *app_id;//
    NSString *service_header;//
    NSString *public_key;//
    NSString *_yx;
    NSString *_checkstate;
}
@property (nonatomic, strong) YJDLoginViewController *loginVC;
@property (nonatomic, strong) YJDZFController *zhifuvc;
@property (nonatomic, strong) NSMutableDictionary *receiveDict;
@property (nonatomic, strong) NSURLSessionTask *task;
@property (nonatomic, strong) YJDUserBtn *userBtn;
@property (nonatomic, strong) NSMutableData *recevieData;
/*
 code == -1 初始化未开始或者还未完成，
 code == 200 初始化成功
 code == 201 断网
 code == 202 网络抛出异常
 code == 203 验签失败
 code == 204 账号错误/密码错误/应用不存在
 code == 300 循环操作
 */
@property (nonatomic, assign) int statusCode;
/**
 *@pragma
 */
@property (nonatomic, copy) NSString *info;
@end

@implementation YJDPlatform


static YJDPlatform*_YJDPlatform;
static dispatch_once_t onceToken;
+ (instancetype)platform
{
    if (!_YJDPlatform)
    {
        dispatch_once(&onceToken,^{
            _YJDPlatform = [[YJDPlatform alloc]init];
            [YJDHelper shareHelp].style = YJDPlatformStyleDefault;
            [YJDHelper shareHelp].layout = YJDPlatformLayoutDefault;
            [YJDHelper shareHelp].color = THEME_COLOR;
            _YJDPlatform.userBtn = [YJDUserBtn yjd_shareUserBtn];
            _YJDPlatform.userBtn.delegate = _YJDPlatform;
        });
    }
    return  _YJDPlatform;
}

- (YJDLoginViewController *)loginVC
{
    if (!_loginVC)
    {
        _loginVC = [[YJDLoginViewController alloc]init];
        _loginVC.delegate = self;
    }
    return _loginVC;
}

- (YJDZFController *)zhifuvc
{
    if (!_zhifuvc)
    {
        _zhifuvc = [[YJDZFController alloc]init];
        _zhifuvc.delegate = self;
    }
    return _zhifuvc;
}

- (NSString *)accountID
{
    return [self.receiveDict valueForKey:@"accountid"];
}

- (NSString *)account
{
    return [YJDHelper shareHelp].account;
}

- (NSString *)token
{
    return [self.receiveDict valueForKey:@"accesstoken"];
}

- (NSString *)appID
{
    return app_id;
}

- (NSString *)serviceHeader
{
    return service_header;
}

- (NSString *)publicKey
{
    return public_key;
}

- (NSString *)yx
{
    return _yx;
}

- (NSString *)state
{
    return _checkstate;
}

- (NSMutableData *)recevieData
{
    if (!_recevieData)
    {
        _recevieData = [[NSMutableData alloc] init];
    }
    return _recevieData;
}

- (NSString *)currentVersion
{
    if ([[NSBundle mainBundle].infoDictionary valueForKey:@"currentversion"])
        return [[NSBundle mainBundle].infoDictionary valueForKey:@"currentversion"];
    else
        return @"1.1.9";
}

+ (void)registerYJDPlatform:(NSString *)appID serviceHeader:(NSString *)serviceHeader publicKey:(NSString *)key
{
    _YJDPlatform = [self platform];
    _YJDPlatform->app_id = appID;
    _YJDPlatform->service_header = serviceHeader;
    _YJDPlatform->public_key = key;
    _YJDPlatform.statusCode = -1;
    _YJDPlatform.info = nil;
    _YJDPlatform.done = NO;
    if (_YJDPlatform.task)
    {
        [_YJDPlatform.task cancel];
        _YJDPlatform.task = nil;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *para = @{@"appid":appID,@"imei":[YJDDevice yjd_deviceIDFV],@"ip":[YJDDevice yjd_deviceIP],@"terminal":@"1"};
        _YJDPlatform.task = [YJDHttps post:INIT_API parameters:para delegate:_YJDPlatform];
    });
}

+ (void)platformStyle:(YJDPlatformStyle)style
{
    [YJDHelper shareHelp].style = style;
}

+ (void)platformLayout:(YJDPlatformLayout)layout
{
    [YJDHelper shareHelp].layout = layout;
}

+ (void)platformColorType:(YJDPlatformColor)type color:(UIColor *)color
{
    if (type == YJDPlatformColorDefault) [YJDHelper shareHelp].color = THEME_COLOR;
    else if (type == YJDPlatformColorRed) [YJDHelper shareHelp].color = RED_COLOR;
    else if (type == YJDPlatformColorBlue) [YJDHelper shareHelp].color = BLUE_COLOR;
    else if (type == YJDPlatformColorOrange) [YJDHelper shareHelp].color = ORANGE_COLOR;
    else if (type == YJDPlatformColorCustom) [YJDHelper shareHelp].color = color;
    
}

+ (void)prepareLogin
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_YJDPlatform.statusCode == 200)
        {
            [YJDHud yjd_stopHud];
            [_YJDPlatform.loginVC yjd_pop];
        }
        else if (_YJDPlatform.statusCode == 300 || _YJDPlatform.statusCode == -1)
        {
            [YJDHud yjd_startHud];
            [YJDPlatform prepareLogin];
        }
        else if ( _YJDPlatform.statusCode == 201 || _YJDPlatform.statusCode == 202 || _YJDPlatform.statusCode == 203 || _YJDPlatform.statusCode == 204)
        {
            [YJDHud yjd_stopHud];
            [YJDAlert yjd_showMessage:[NSString stringWithFormat:@"%d:%@",_YJDPlatform.statusCode,_YJDPlatform.info] hidden:^{
                [YJDPlatform registerYJDPlatform:_YJDPlatform.appID serviceHeader:_YJDPlatform.serviceHeader publicKey:_YJDPlatform.publicKey];
                _YJDPlatform.statusCode = 300;
                [YJDPlatform prepareLogin];
            }];
        }
    });
}

+ (void)prepareRegister
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_YJDPlatform.statusCode == 200)
        {
            [YJDHud yjd_stopHud];
            [[[YJDRegisterViewController alloc] init] yjd_pop];
        }
        else if (_YJDPlatform.statusCode == 300 || _YJDPlatform.statusCode == -1)        {
            [YJDHud yjd_startHud];
            [YJDPlatform prepareRegister];
        }
        else if ( _YJDPlatform.statusCode == 201 || _YJDPlatform.statusCode == 202 || _YJDPlatform.statusCode == 203 || _YJDPlatform.statusCode == 204)
        {
            [YJDHud yjd_stopHud];
            [YJDAlert yjd_showMessage:[NSString stringWithFormat:@"%d:%@",_YJDPlatform.statusCode,_YJDPlatform.info] hidden:^{
                [YJDHud yjd_startHud];
                [YJDPlatform registerYJDPlatform:_YJDPlatform.appID serviceHeader:_YJDPlatform.serviceHeader publicKey:_YJDPlatform.publicKey];
                _YJDPlatform.statusCode = 300;
                [YJDPlatform prepareRegister];
            }];
        }
        
    });
}

+ (void)zunbeizhifu:(YJDProduct *)product
{
    if ([_YJDPlatform.accountID length] < 1 || [_YJDPlatform.token length] < 1)
    {
        [YJDAlert yjd_showInWindowWithTitle:@"错误" message:@"检测到您未登录，请先登录" complete:^{
            [self prepareLogin];
        }];
    }
    else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [_YJDPlatform.zhifuvc yjd_zunbeizf:product];
        });
    }
    
}

- (void)yjd_setupCallback
{
    if (!self.delegate && self.callback)
    {
        self.callback(self.receiveDict);
    }
    else if (self.delegate && [self.delegate respondsToSelector:@selector(receiveCallBack:)])
    {
        [self.delegate receiveCallBack:self.receiveDict];
    }
}

#pragma mark - SKLLoginViewControllerDelegate---Method
- (void)yjd_didreceiveDictYJDLoginViewController:(NSDictionary *)dict
{
    self.receiveDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    if (VERSION_2_0_0_LATER)
    {
        if ([[dict valueForKey:@"bindstate"] intValue] == 0)
        {
            //            [YJDPlatform yjd_authenticate];//弹出认证窗口
        }
        else
        {
            [self yjd_setupCallback];
        }
    }
    else
    {
        [self yjd_setupCallback];
    }
}

#pragma mark - SKLRZViewControllerDelegate---Method
- (void)yjd_actionForAuthenticate
{
    if (VERSION_2_0_0_LATER)
    {
        if ([[self.receiveDict valueForKey:@"phone"] length] < 1)
        {
            //             [NSClassFromString(@"SKLBindViewController") yjd_show];
        }
    }
    [self yjd_setupCallback];
}

#pragma mark - YJDZFControllerDelegate
- (void)yjd_didReceiveFromYJDZFController:(YJDProduct *)product
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(receiveCallBack:)])
    {
        [self.delegate receiveCallBack:nil];
    }
}

#pragma mark - YJDUserViewControllerDelegate
- (void)yjd_YJDUserViewControllerDelegate
{
    [YJDPlatform prepareLogin];
}

#pragma mark - NSURLSessionDelegate method
//接受到服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //__FUNCTION__ c语言字符串用s
    DeLog(@"1。 %s",__FUNCTION__);
    //允许服务器回传数据
    completionHandler(NSURLSessionResponseAllow);
}

//接受服务器回传的数据可能执行多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [_YJDPlatform.recevieData appendData:data];
}

//请求成功或者失败
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error{
    //    DeLog(@"3。%@",error);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error
{
    if (error && (error.code != -999 || ![error.localizedDescription isEqualToString:@"cancelled"]))
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            _YJDPlatform.statusCode = 202;
            _YJDPlatform.done = YES;
            _YJDPlatform.info = [NSString stringWithFormat:@"%@",error.localizedDescription];
        });
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        NSError *newError;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_YJDPlatform.recevieData options:NSJSONReadingMutableLeaves error:&newError];
        _YJDPlatform.done = YES;
        if (newError)
        {
            _YJDPlatform.recevieData = nil;
            NSLog(@"initSDK error === %@",[newError localizedDescription]);
        }
        NSString *sign = [dict valueForKey:@"sign"];
        NSString *transdata = [dict valueForKey:@"transdata"];
        BOOL isSuccess =  [transdata yjd_verifySign:sign];
        if (isSuccess)
        {
            NSDictionary *transDict =  [transdata yjd_rc4_dec: _YJDPlatform.appID];
            _YJDPlatform.info = [transDict valueForKey:@"info"];
            int  code = [[transDict valueForKey:@"code"] intValue];
            
            if (code == 100)
            {
                _YJDPlatform.statusCode = 200;
                _YJDPlatform->_yx = [transDict valueForKey:@"gameurl"];
                _YJDPlatform->_checkstate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"checkstate"]];
                _YJDPlatform.userBtn.hidden = ([[transDict valueForKey:@"floatstate"] intValue] == 0)?YES:NO;
                DeLog(@"初始化成功");
                LoadingViewController *vc = (LoadingViewController *)[UIView yjd_keyWindow].rootViewController;
                [vc load];
            }
            else
            {
                _YJDPlatform.statusCode = code;
            }
        }
        else
        {
            _YJDPlatform.info = @"网络不给力或已断开，请检查网络";
            _YJDPlatform.statusCode = 204;
        }
        _YJDPlatform.recevieData = nil;
    });
    [session finishTasksAndInvalidate];
}
@end


